// script.js - 修复数据加载路径问题
// 全局变量
let map;                   // 地图实例
let currentMarkers = [];   // 当前显示的标注数组
let disasterData = {       // 灾害数据
    days: [],              // 按天存储的数据
    startDate: "",
    endDate: "",
    earthquakeEvents: []   // 地震事件数据（主震余震）
};

let isPlaying = false;     // 是否正在播放
let playInterval;          // 播放定时器
let currentDayIndex = 0;   // 当前天数索引
let currentMinuteIndex = 0; // 当前分钟索引
let currentDimension = 'time'; // 当前维度：time, space
let heatmap = null;        // 热力图实例
let currentInfoWindow = null; // 当前信息窗口
let roadData = []; // 存储道路数据
let roadPolylines = []; // 存储道路折线对象

// 状态图标映射
const STATUS_ICONS = {
  'intact': new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
    scale: 16,  // 增大图标尺寸，便于点击
    strokeWeight: 2,
    strokeColor: '#ffffff',
    fillColor: '#00FF00', // 绿色点
    zIndex: 999  // 提高z-index确保可点击
  }),
  'damaged': new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
    scale: 16,
    strokeWeight: 2,
    strokeColor: '#ffffff',
    fillColor: '#FFFF00', // 黄色点
    zIndex: 999
  }),
  'collapsed': new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
    scale: 16,
    strokeWeight: 2,
    strokeColor: '#ffffff',
    fillColor: '#FF0000', // 红色点
    zIndex: 999
  })
};

// 初始化地图
function initMap() {
    console.log("开始初始化地图");
    
    try {
        map = new BMap.Map('map-container');
        
        // 设置地图中心点和推荐缩放级别
        const initPoint = new BMap.Point(103.492087, 31.058125);
        map.centerAndZoom(initPoint, 15);
        
        // 添加缩放控件
        map.addControl(new BMap.NavigationControl());
        map.enableScrollWheelZoom(true);
        map.setMapType(BMAP_SATELLITE_MAP);
        
        // 添加地图类型切换事件
        map.addEventListener('maptypechange', function() {
            if (this.getMapType().getName() === 'BMAP_SATELLITE_MAP') {
                this.setMinZoom(10);
                this.setMaxZoom(18);
            }
        });
        
        // 添加地图点击事件，关闭信息窗口
        map.addEventListener('click', function() {
            if (currentInfoWindow) {
                map.closeInfoWindow();
                currentInfoWindow = null;
            }
        });
        
        console.log("地图初始化完成");
        return true;
    } catch (error) {
        console.error("地图初始化失败:", error);
        return false;
    }
}

// 显示标记信息
function showMarkerInfo(feature) {
    console.log("显示标记信息:", feature);
    
    let infoContent = '';
    if (feature.properties) {
        // 灾害点信息 - 添加跳转按钮
        infoContent = `
            <div class="info-window-content">
                <div class="info-window-title">${feature.properties.name || '未命名地点'}</div>
                <div class="info-window-item">
                    <span class="info-window-label">状态:</span>
                    <span class="info-window-value">${getStatusText(feature.status)}</span>
                </div>
                <div class="info-window-item">
                    <span class="info-window-label">类型:</span>
                    <span class="info-window-value">${feature.properties.type_detail || '未知'}</span>
                </div>
                <div class="info-window-item">
                    <span class="info-window-label">损坏情况:</span>
                    <span class="info-window-value">${feature.properties.damage || '未知'}</span>
                </div>
                <div class="info-window-item">
                    <span class="info-window-label">风险:</span>
                    <span class="info-window-value">${feature.properties.risk || '未知'}</span>
                </div>
                <button class="jump-button" data-building-id="${feature.properties.id || ''}">查看详细报告</button>
            </div>
        `;
    } else if (feature.magnitude) {
        // 地震事件信息
        infoContent = `
            <div class="info-window-content">
                <div class="info-window-title">${feature.phase || '地震事件'}</div>
                <div class="info-window-item">
                    <span class="info-window-label">震级:</span>
                    <span class="info-window-value">${feature.magnitude}</span>
                </div>
                <div class="info-window-item">
                    <span class="info-window-label">时间:</span>
                    <span class="info-window-value">${feature.time || '未知'}</span>
                </div>
                <div class="info-window-item">
                    <span class="info-window-label">坐标:</span>
                    <span class="info-window-value">${feature.coordinates[0].toFixed(4)}, ${feature.coordinates[1].toFixed(4)}</span>
                </div>
                <div class="info-window-item">
                    <span class="info-window-label">深度:</span>
                    <span class="info-window-value">${feature.depth || '未知'} km</span>
                </div>
                <div class="info-window-item">
                    <span class="info-window-label">影响范围:</span>
                    <span class="info-window-value">${feature.affectedArea || '未知'} km²</span>
                </div>
            </div>
        `;
    } else {
        infoContent = `<div class="info-window-content">未知标记类型</div>`;
    }
    
    // 关闭所有现有信息窗口
    map.closeInfoWindow();
    
    // 创建新信息窗口
    const infoWindow = new BMap.InfoWindow(infoContent, {
        width: 320,
        height: 350,
        title: "详细信息",
        enableMessage: false
    });
    
    // 保存当前信息窗口引用
    currentInfoWindow = infoWindow;
    
    // 获取标记位置并打开信息窗口
    const point = new BMap.Point(feature.coordinates[0], feature.coordinates[1]);
    map.openInfoWindow(infoWindow, point);
    
    // 添加信息窗口加载完成后的处理
    setTimeout(() => {
        // 为跳转按钮添加事件监听
        const jumpButton = document.querySelector('.jump-button');
        if (jumpButton) {
            jumpButton.addEventListener('click', function() {
                const buildingId = this.getAttribute('data-building-id');
                if (buildingId) {
                    jumpToBuildingDetail(feature);
                }
            });
        }
    }, 100);
}

// 跳转到建筑物详情页
function jumpToBuildingDetail(feature) {
    console.log("跳转到建筑物详情:", feature);
    
    try {
        // 创建简化版的对象，避免循环引用问题
        const buildingData = {
            properties: feature.properties,
            coordinates: feature.coordinates,
            status: feature.status
        };
        
        // 使用更可靠的数据存储方式
        const storageKey = 'selectedBuilding';
        const storageData = JSON.stringify(buildingData);
        
        // 验证存储是否成功
        sessionStorage.setItem(storageKey, storageData);
        const verify = sessionStorage.getItem(storageKey);
        
        if (verify === storageData) {
            console.log("数据存储验证成功，准备跳转");
            // 使用setTimeout确保页面有足够时间处理存储操作
            setTimeout(() => {
                window.location.href = 'building-detail.html';
            }, 50);
        } else {
            console.error("数据存储验证失败");
            alert('数据保存失败，请重试');
        }
    } catch (error) {
        console.error("存储数据到sessionStorage失败: ", error);
        alert('跳转失败: ' + error.message);
    }
}

// 更新余震信息侧边栏
function updateAftershockSidebar() {
    const sidebar = document.getElementById('aftershock-list');
    if (!sidebar) return;
    
    // 清空现有内容
    sidebar.innerHTML = '';
    
    // 获取当前时间之前的所有地震事件
    const currentTime = getCurrentDateTime();
    const pastEarthquakes = disasterData.earthquakeEvents.filter(event => {
        const eventTime = new Date(event.time);
        return eventTime <= currentTime;
    });
    
    // 按时间倒序排列
    pastEarthquakes.sort((a, b) => new Date(b.time) - new Date(a.time));
    
    // 添加地震事件到侧边栏
    pastEarthquakes.forEach(event => {
        const eventTime = new Date(event.time);
        const formattedTime = `${eventTime.getFullYear()}-${(eventTime.getMonth() + 1).toString().padStart(2, '0')}-${eventTime.getDate().toString().padStart(2, '0')} ${eventTime.getHours().toString().padStart(2, '0')}:${eventTime.getMinutes().toString().padStart(2, '0')}:${eventTime.getSeconds().toString().padStart(2, '0')}`;
        
        // 确定震级类别
        let magnitudeClass = 'magnitude-low';
        if (event.magnitude >= 5.0) {
            magnitudeClass = 'magnitude-medium';
        }
        if (event.magnitude >= 7.0) {
            magnitudeClass = 'magnitude-high';
        }
        
        const eventElement = document.createElement('div');
        eventElement.className = 'aftershock-item';
        eventElement.innerHTML = `
            <div class="aftershock-time">${formattedTime}</div>
            <div class="aftershock-magnitude">
                <span class="magnitude-value ${magnitudeClass}">${event.magnitude.toFixed(1)}</span>
                ${event.type === 'main' ? '主震' : '余震'}
            </div>
            <div class="aftershock-location">${getLocationName(event.coordinates)}</div>
            <div class="aftershock-coordinates">${event.coordinates[0].toFixed(4)}°E, ${event.coordinates[1].toFixed(4)}°N</div>
        `;
        
        sidebar.appendChild(eventElement);
    });
    
    // 如果没有地震事件，显示提示信息
    if (pastEarthquakes.length === 0) {
        sidebar.innerHTML = '<div class="aftershock-item">暂无地震事件数据</div>';
    }
}

// 根据坐标获取位置名称（简化版）
function getLocationName(coordinates) {
    // 这里可以根据坐标返回具体位置名称
    // 简化版：只返回一个固定名称
    return "四川省汶川县附近";
}

// 获取当前日期时间（基于播放进度）
function getCurrentDateTime() {
    const dayData = disasterData.days[currentDayIndex];
    if (!dayData) return new Date();
    
    const baseDate = new Date(dayData.date);
    const minutes = currentMinuteIndex;
    
    // 添加分钟数
    baseDate.setMinutes(baseDate.getMinutes() + minutes);
    
    return baseDate;
}

// 日期格式化函数
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}年${month}月${day}日`;
}

// 时间格式化函数（分钟转时间）
function formatTime(minutes) {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
}

// 加载灾害数据
async function loadDisasterData() {
    try {
        // 清空现有数据
        disasterData.days = [];
        
        // 加载多天的数据（假设有14天）
        for (let day = 1; day <= 14; day++) {
            try {
                // 修改路径，从data文件夹加载
                const response = await fetch(`data/disaster-data-day${day}.json`);
                if (!response.ok) {
                    console.warn(`第${day}天的数据文件不存在或无法访问`);
                    continue; // 跳过不存在的文件
                }
                
                const dayData = await response.json();
                
                // 转换数据格式以匹配代码结构
                const formattedDayData = {
                    day: dayData.day,
                    date: dayData.date,
                    timeline: dayData.timeline.map(timePoint => ({
                        time: timePoint.time,
                        features: timePoint.features.map(feature => ({
                            type: "Feature",
                            properties: {
                                id: feature.properties.id,
                                name: feature.properties.name,
                                type_detail: feature.properties.type_detail,
                                damage: feature.properties.damage,
                                risk: feature.properties.risk
                            },
                            coordinates: feature.coordinates,
                            status: feature.status
                        }))
                    }))
                };
                
                disasterData.days.push(formattedDayData);
                console.log(`第${day}天数据加载成功`, formattedDayData);
            } catch (error) {
                console.warn(`加载第${day}天数据失败:`, error);
            }
        }
        
        // 设置开始和结束日期
        if (disasterData.days.length > 0) {
            disasterData.startDate = disasterData.days[0].date;
            disasterData.endDate = disasterData.days[disasterData.days.length - 1].date;
            
            console.log("灾害数据加载完成", disasterData.days);
            
            // 初始化时间滑块
            initTimeSlider();
            
            // 初始化天数选择器
            initDaySelector();
            
            // 显示第一天第0分钟的数据
            showFrame(0, 0);
        }
    } catch (error) {
        console.error("加载灾害数据失败:", error);
    }
}


// 初始化天数选择器
function initDaySelector() {
    const dayButtons = document.querySelectorAll('.day-btn');
    
    dayButtons.forEach(button => {
        const day = parseInt(button.getAttribute('data-day'));
        
        // 检查这一天是否有数据
        const dayData = disasterData.days.find(d => d.day === day);
        if (!dayData) {
            button.disabled = true;
            button.style.opacity = '0.5';
        }
        
        button.addEventListener('click', () => {
            // 更新按钮状态
            dayButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            
            // 切换到选中的天数
            switchToDay(day);
        });
    });
    
    // 默认激活第一天
    if (dayButtons.length > 0 && disasterData.days.length > 0) {
        const firstButton = document.querySelector('.day-btn[data-day="1"]');
        if (firstButton) firstButton.classList.add('active');
    }
}

// 切换到指定天数
function switchToDay(day) {
    const dayIndex = disasterData.days.findIndex(d => d.day === day);
    if (dayIndex === -1) return;
    
    currentDayIndex = dayIndex;
    currentMinuteIndex = 0;
    
    // 显示当前天的数据
    showFrame(dayIndex, 0);
    
    // 更新时间滑块范围
    const slider = document.getElementById('time-slider');
    const dayData = disasterData.days[dayIndex];
    if (dayData && dayData.timeline) {
        slider.max = dayData.timeline.length > 0 ? dayData.timeline.length - 1 : 0;
    } else {
        slider.max = 0;
    }
    slider.value = 0;
}

// 初始化时间滑块
function initTimeSlider() {
    const slider = document.getElementById('time-slider');
    slider.min = 0;
    
    // 设置第一天的时间滑块范围
    if (disasterData.days.length > 0 && disasterData.days[0].timeline) {
        slider.max = disasterData.days[0].timeline.length > 0 ? disasterData.days[0].timeline.length - 1 : 0;
    } else {
        slider.max = 0;
    }
    
    slider.value = 0;
    
    // 添加滑块事件监听
    slider.addEventListener('input', function() {
        const minuteIndex = parseInt(this.value);
        showFrame(currentDayIndex, minuteIndex);
    });
}

// 显示指定天数和分钟的数据
function showFrame(dayIndex, minuteIndex) {
    const dayData = disasterData.days[dayIndex];
    if (!dayData) return;
    
    // 确保分钟索引在有效范围内
    if (dayData.timeline && dayData.timeline.length > 0) {
        minuteIndex = Math.max(0, Math.min(minuteIndex, dayData.timeline.length - 1));
    } else {
        minuteIndex = 0;
    }
    
    // 更新当前索引
    currentDayIndex = dayIndex;
    currentMinuteIndex = minuteIndex;
    
    // 更新UI显示
    document.getElementById('current-day').textContent = `第${dayData.day}天`;
    document.getElementById('current-date').textContent = formatDate(dayData.date);
    
    // 更新时间显示
    if (dayData.timeline && dayData.timeline[minuteIndex]) {
        const timeData = dayData.timeline[minuteIndex];
        document.getElementById('current-time').textContent = timeData.time ? timeData.time.split('T')[1].substring(0, 5) : formatTime(minuteIndex);
    } else {
        document.getElementById('current-time').textContent = formatTime(minuteIndex);
    }
    
    // 更新滑块位置
    document.getElementById('time-slider').value = minuteIndex;
    
    // 清除现有标记
    clearMarkers();
    
    // 添加新标记
    if (dayData.timeline && dayData.timeline[minuteIndex] && dayData.timeline[minuteIndex].features) {
        dayData.timeline[minuteIndex].features.forEach(feature => {
            addDisasterMarker(feature);
        });
    }
    
    // 更新余震信息侧边栏
    updateAftershockSidebar();
   // 更新道路状态
    updateRoadStatus();
}

// 添加灾害标记（修复版本）
function addDisasterMarker(feature) {
    const point = new BMap.Point(feature.coordinates[0], feature.coordinates[1]);
    
    // 创建标记
    const icon = STATUS_ICONS[feature.status] || STATUS_ICONS.intact;
    const marker = new BMap.Marker(point, { icon: icon });

    // 添加特征数据到标记对象
    marker.feature = feature;
    
    // 添加点击事件 - 只显示信息窗口，不跳转
    marker.addEventListener('click', function(e) {
        console.log("标记被点击，显示信息窗口");
        showMarkerInfo(this.feature);
    });
    
    // 添加到地图和当前标记数组
    map.addOverlay(marker);
    currentMarkers.push(marker);
    
    return marker;
}

// 清除所有标记
function clearMarkers() {
    // 从地图移除所有标记
    currentMarkers.forEach(marker => {
        map.removeOverlay(marker);
    });
    
    // 清空标记数组
    currentMarkers = [];
}

// 状态文本转换
function getStatusText(status) {
    const statusMap = {
        'intact': '基本完好',
        'damaged': '损坏',
        'collapsed': '倒塌'
    };
    return statusMap[status] || status;
}

// 播放控制
function playFrames() {
    if (isPlaying) return;
    
    isPlaying = true;
    document.getElementById('play-pause-btn').textContent = '⏸ 暂停';
    
    // 如果不在时间维度，自动切换到时间维度
    if (currentDimension !== 'time') {
        switchToDimension('time');
    }
    
    // 获取播放速度
    const speedSelect = document.getElementById('speed-select');
    const speed = parseInt(speedSelect.value);
    
    // 播放函数
    const playNextFrame = () => {
        if (!isPlaying) return;
        
        const currentDayData = disasterData.days[currentDayIndex];
        if (!currentDayData) {
            pausePlayback();
            return;
        }
        
        // 检查是否到达当前天的最后一分钟
        if (currentMinuteIndex >= (currentDayData.timeline ? currentDayData.timeline.length - 1 : 0)) {
            // 检查是否有下一天
            if (currentDayIndex < disasterData.days.length - 1) {
                // 切换到下一天
                currentDayIndex++;
                currentMinuteIndex = 0;
                
                // 更新天数选择器
                const dayButtons = document.querySelectorAll('.day-btn');
                dayButtons.forEach(button => {
                    button.classList.remove('active');
                    if (parseInt(button.getAttribute('data-day')) === disasterData.days[currentDayIndex].day) {
                        button.classList.add('active');
                    }
                });
                
                // 更新时间滑块范围
                const slider = document.getElementById('time-slider');
                const nextDayData = disasterData.days[currentDayIndex];
                if (nextDayData && nextDayData.timeline) {
                    slider.max = nextDayData.timeline.length > 0 ? nextDayData.timeline.length - 1 : 0;
                }
            } else {
                // 已经是最后一天，停止播放
                pausePlayback();
                return;
            }
        } else {
            // 前进到下一分钟
            currentMinuteIndex++;
        }
        
        // 显示当前帧
        showFrame(currentDayIndex, currentMinuteIndex);
        
        // 继续播放
        playInterval = setTimeout(playNextFrame, speed);
    };
    
    // 开始播放
    playInterval = setTimeout(playNextFrame, speed);
}

// 暂停播放
function pausePlayback() {
    isPlaying = false;
    clearTimeout(playInterval);
    document.getElementById('play-pause-btn').textContent = '▶ 播放';
}

// 切换维度
function switchToDimension(dimension) {
    currentDimension = dimension;
    
    // 更新按钮状态
    document.querySelectorAll('.dimension-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.getElementById(`${dimension}-dimension`).classList.add('active');
    
    // 更新图例显示
    document.getElementById('damage-legend').classList.add('hidden');
    document.getElementById('space-legend').classList.add('hidden');
    
    if (dimension === 'time') {
        document.getElementById('damage-legend').classList.remove('hidden');
    } else if (dimension === 'space') {
        document.getElementById('space-legend').classList.remove('hidden');
    }
    
    // 清除现有标记
    clearMarkers();
    
    // 根据选中的维度显示数据
    if (dimension === 'time') {
        showFrame(currentDayIndex, currentMinuteIndex);
    } else if (dimension === 'space') {
        showSpaceDimension();
    }
}

// 显示空间维度
function showSpaceDimension() {
    // 清除现有标记
    clearMarkers();
    
    // 如果有热力图，显示它
    if (heatmap) {
        heatmap.show();
        return;
    }
    
    // 准备热力图数据
    const heatmapData = [];
    
    disasterData.days.forEach(day => {
        if (day.timeline) {
            day.timeline.forEach(minute => {
                if (minute.features) {
                    minute.features.forEach(feature => {
                        // 根据破坏程度设置权重
                        let weight = 0.3;
                        if (feature.status === 'damaged') {
                            weight = 0.6;
                        } else if (feature.status === 'collapsed') {
                            weight = 1.0;
                        }
                        
                        heatmapData.push({
                            lng: feature.coordinates[0],
                            lat: feature.coordinates[1],
                            count: weight
                        });
                    });
                }
            });
        }
    });
    
    // 创建热力图
    heatmap = new BMapLib.HeatmapOverlay({
        radius: 30,
        opacity: 0.6
    });
    
    map.addOverlay(heatmap);
    heatmap.setDataSet({
        data: heatmapData,
        max: 1.0
    });
    
    // 更新余震信息侧边栏
    updateAftershockSidebar();
}

// 加载地震事件数据
async function loadEarthquakeData() {
    try {
        // 修改路径，从data文件夹加载
        const response = await fetch('data/earthquake-events.json');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 转换数据格式以匹配代码结构
        disasterData.earthquakeEvents = data.events.map(event => ({
            id: event.id,
            type: event.type,
            magnitude: event.magnitude,
            time: event.time,
            coordinates: event.coordinates,
            depth: event.depth,
            affectedArea: event.affectedArea,
            phase: event.phase
        }));
        
        console.log('地震事件数据加载成功', disasterData.earthquakeEvents);
        
        // 更新余震信息侧边栏
        updateAftershockSidebar();
        
        // 在地图上标记地震事件
        plotEarthquakes();
    } catch (error) {
        console.error('加载地震事件数据失败:', error);
        
        // 在地图上标记地震事件
        plotEarthquakes();
    }
}

// 在地图上绘制地震事件
function plotEarthquakes() {
    // 清除现有的地震标记
    currentMarkers.forEach(marker => {
        if (marker.isEarthquake) {
            map.removeOverlay(marker);
        }
    });
    
    // 过滤出非地震标记
    currentMarkers = currentMarkers.filter(marker => !marker.isEarthquake);
    
    // 添加地震标记
    disasterData.earthquakeEvents.forEach(event => {
        const point = new BMap.Point(event.coordinates[0], event.coordinates[1]);
        
        // 创建地震标记（使用不同颜色和大小表示震级）
        const magnitudeSize = Math.min(30, Math.max(10, event.magnitude * 3));
        const earthquakeIcon = new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
            scale: magnitudeSize,
            strokeWeight: 2,
            strokeColor: '#ffffff',
            fillColor: event.type === 'main' ? '#FF0000' : '#FFA500', // 主震红色，余震橙色
            zIndex: 1000 // 最高z-index确保在地震标记在最上层
        });
        
        const marker = new BMap.Marker(point, { icon: earthquakeIcon });
        marker.isEarthquake = true; // 标记为地震点
        marker.feature = event; // 存储地震数据
        
        // 添加点击事件
        marker.addEventListener('click', function() {
            showMarkerInfo(this.feature);
        });
        
        // 添加到地图和当前标记数组
        map.addOverlay(marker);
        currentMarkers.push(marker);
    });
}

// 页面加载完成后执行
window.onload = async function() {
    console.log("页面加载完成，开始初始化");
    
    // 等待百度地图API加载完成
    if (typeof BMap === 'undefined') {
        console.error("百度地图API未加载");
        // 重新尝试加载
        setTimeout(() => {
            if (typeof BMap !== 'undefined') {
                initMap();
            } else {
                alert("地图加载失败，请刷新页面重试");
            }
        }, 1000);
        return;
    }
    
    // 初始化地图
    if (!initMap()) {
        alert("地图初始化失败，请检查网络连接");
        return;
    }
    
    // 并行加载灾害数据和地震数据
    await Promise.allSettled([
        loadDisasterData(),
        loadEarthquakeData(),
        loadRoadData()
    ]);
    
    // 默认显示时间维度
    switchToDimension('time');
    
    // 绑定播放/暂停按钮事件
    document.getElementById('play-pause-btn').addEventListener('click', function() {
        if (isPlaying) {
            pausePlayback();
        } else {
            playFrames();
        }
    });
    
    // 绑定速度选择事件
    document.getElementById('speed-select').addEventListener('change', function() {
        // 如果正在播放，重新开始播放以应用新的速度
        if (isPlaying) {
            pausePlayback();
            playFrames();
        }
    });
    
    // 绑定维度切换事件
    document.getElementById('time-dimension').addEventListener('click', function() {
        switchToDimension('time');
    });
    
    document.getElementById('space-dimension').addEventListener('click', function() {
        switchToDimension('space');
    });
    
    console.log("初始化完成");
};

// 在页面加载完成后添加道路数据加载
async function loadRoadData() {
    try {
        // 加载道路数据
        const response = await fetch('data/roads-data.json');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        roadData = data.features;
        console.log('道路数据加载成功', roadData);
        
        // 在地图上绘制道路
        plotRoads();
    } catch (error) {
        console.error('加载道路数据失败:', error);
    }
}


// 在地图上绘制道路
function plotRoads() {
    // 清除现有的道路
    clearRoads();
    
    // 绘制每条道路
    roadData.forEach(road => {
        const points = road.geometry.coordinates.map(coord => 
            new BMap.Point(coord[0], coord[1])
        );
        
        // 初始颜色为绿色（通畅）
        const polyline = new BMap.Polyline(points, {
            strokeColor: "green",
            strokeWeight: 5,
            strokeOpacity: 0.8
        });
        
        // 存储道路ID以便后续更新
        polyline.roadId = road.properties.id;
        map.addOverlay(polyline);
        roadPolylines.push(polyline);
    });
    
    console.log("道路绘制完成");
}

// 清除所有道路
function clearRoads() {
    roadPolylines.forEach(polyline => {
        map.removeOverlay(polyline);
    });
    roadPolylines = [];
}

// 更新道路状态
function updateRoadStatus() {
    // 获取当前帧的所有建筑物
    const currentDayData = disasterData.days[currentDayIndex];
    if (!currentDayData || !currentDayData.timeline) return;
    
    const currentMinuteData = currentDayData.timeline[currentMinuteIndex];
    if (!currentMinuteData || !currentMinuteData.features) return;
    
    const currentBuildings = currentMinuteData.features;
    
    // 重置所有道路为绿色
    roadPolylines.forEach(polyline => {
        polyline.setStrokeColor("green");
        polyline.setStrokeWeight(5);
    });
    
    // 检查每个建筑物对道路的影响
    currentBuildings.forEach(building => {
        // 只处理损坏或倒塌的建筑物
        if (building.status === 'damaged' || building.status === 'collapsed') {
            // 查找附近的道路
            const affectedRoads = findNearbyRoads(building.coordinates);
            
            // 更新道路状态
            affectedRoads.forEach(road => {
                const polyline = roadPolylines.find(p => p.roadId === road.properties.id);
                if (polyline) {
                    if (building.status === 'collapsed') {
                        // 完全倒塌 - 道路红色阻塞
                        polyline.setStrokeColor("red");
                        polyline.setStrokeWeight(8);
                    } else if (building.status === 'damaged' && polyline.getStrokeColor() !== 'red') {
                        // 部分损坏 - 道路黄色部分阻塞（仅当不是红色时）
                        polyline.setStrokeColor("yellow");
                        polyline.setStrokeWeight(6);
                    }
                }
            });
        }
    });
}

// 查找建筑物附近的道路
function findNearbyRoads(buildingCoords, maxDistance = 0.00015) {
    const nearbyRoads = [];
    
    roadData.forEach(road => {
        // 检查道路线段是否靠近建筑物
        const coordinates = road.geometry.coordinates;
        for (let i = 0; i < coordinates.length - 1; i++) {
            const distance = pointToLineDistance(
                buildingCoords,
                coordinates[i],
                coordinates[i + 1]
            );
            
            if (distance < maxDistance) {
                nearbyRoads.push(road);
                break; // 找到一条就跳出循环
            }
        }
    });
    
    return nearbyRoads;
}

// 计算点到线段的距离
function pointToLineDistance(point, lineStart, lineEnd) {
    const x = point[0], y = point[1];
    const x1 = lineStart[0], y1 = lineStart[1];
    const x2 = lineEnd[0], y2 = lineEnd[1];
    
    const A = x - x1;
    const B = y - y1;
    const C = x2 - x1;
    const D = y2 - y1;
    
    const dot = A * C + B * D;
    const len_sq = C * C + D * D;
    let param = -1;
    
    if (len_sq !== 0) {
        param = dot / len_sq;
    }
    
    let xx, yy;
    
    if (param < 0) {
        xx = x1;
        yy = y1;
    } else if (param > 1) {
        xx = x2;
        yy = y2;
    } else {
        xx = x1 + param * C;
        yy = y1 + param * D;
    }
    
    const dx = x - xx;
    const dy = y - yy;
    
    return Math.sqrt(dx * dx + dy * dy);
}